package com.learn.core.controller.learn;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.learn.common.annotation.UserLoginToken;
import com.learn.common.enums.ResultEnum;
import com.learn.common.utils.DateUtils;
import com.learn.common.utils.JwtUtil;
import com.learn.common.utils.ResultUtil;
import com.learn.common.utils.StringUtils;
import com.learn.common.utils.http.OkHttps;
import com.learn.common.utils.result.CommonResult;
import com.learn.core.domain.*;
import com.learn.core.domain.view.ExamTarget;
import com.learn.core.domain.view.UserDetailsGather;
import com.learn.core.service.*;
import com.learn.framework.web.controller.WebController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Description
 * @author zhaohongyu
 * @ClassName ExamController
 * @date 2021.04.12 17:13
 * @describe 考试
 */
@Api("考试")
@RestController
@RequestMapping("/learn/exam")
public class ExamController  extends WebController<LExam> {

    @Autowired
    private ILExamService ilExamService;
    @Autowired
    private ILExamUserService ilExamUserService;
    @Autowired
    private ILExamPaperService ilExamPaperService;
    @Autowired
    private ILOrganizationService ilOrganizationService;
    @Autowired
    private ILExamSortService ilExamSortService;
    @Autowired
    private IExamTargetService iExamTargetService;
    @Autowired
    private IUserDetailsGatherService iUserDetailsGatherService;
    @Autowired
    private ILGroupingUserService ilGroupingUserService;

    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    //进行中的考试列表
    @ApiOperation(value = "进行中的考试列表")
    @UserLoginToken
    @PostMapping("/progressExam")
    public CommonResult<Object> progressExam(HttpServletRequest request){
        String  token = request.getHeader("token");
        String userId = JwtUtil.getUserId(token);
        try {
            // 用户信息
            UserDetailsGather userDetailsGather = userInfo(userId);
            // 用户分组
            List userGroup = userGroup(userId);

            Date date = new Date();
            String startTime = simpleDateFormat.format(date);
            String endTime = simpleDateFormat.format(date);
            QueryWrapper<ExamTarget> queryWrapper = new QueryWrapper<ExamTarget>();
            queryWrapper.eq("release_state","1");
            queryWrapper.eq("type","1");
            queryWrapper.apply(" ((timing_type != '2' AND failure_time > '"+startTime +"') " +
                    "or (timing_type = '2' AND timing_start_time <= '"+startTime +"' AND timing_end_time >= '"+endTime +"'))");
            if(userGroup.size() > 0){
                queryWrapper.and(i -> i.eq("exam_target_type","0").eq("exam_target", userDetailsGather.getOrganizationId())
                        .or(a -> a.eq("exam_target_type", "1").in("exam_target", userGroup)));
            }else{
                queryWrapper.and(i -> i.eq("exam_target_type","0").eq("exam_target", userDetailsGather.getOrganizationId()));
            }
            queryWrapper.orderByAsc("release_time");
            List<ExamTarget> list = iExamTargetService.list(queryWrapper);
            for (ExamTarget examTarget : list) {
                QueryWrapper<LExamUser> lExamUserQueryWrapper = new QueryWrapper<LExamUser>();
                lExamUserQueryWrapper.eq("exam_id",examTarget.getExamId());
                lExamUserQueryWrapper.eq("user_id",userId);
                LExamUser lExamUser = ilExamUserService.getOne(lExamUserQueryWrapper);
                if(null != lExamUser){
                    examTarget.setUserExam("1");
                }else{
                    examTarget.setUserExam("0");
                }
                LOrganization lOrganization = ilOrganizationService.getById(examTarget.getOrganizationId());
                if(null != lOrganization)
                    examTarget.setOrganizationName(lOrganization.getOrganizationName());
                LExamSort lExamSort = ilExamSortService.getById(examTarget.getExamSortId());
                if(null != lExamSort)
                    examTarget.setExamSortName(lExamSort.getExamSortName());
                QueryWrapper countWrapper = new QueryWrapper<LExamUser>();
                countWrapper.eq("user_id",userId);
                countWrapper.eq("exam_id",examTarget.getExamId());
                countWrapper.eq("exam_user_state","2");
                int count = ilExamUserService.count(countWrapper);
                examTarget.setCount(count);
                countWrapper = new QueryWrapper<LExamUser>();
                countWrapper.eq("user_id",userId);
                countWrapper.eq("exam_id",examTarget.getExamId());
                countWrapper.ne("exam_user_state","2");
                int counttype = ilExamUserService.count(countWrapper);
                examTarget.setCountType(counttype);
            }
            return (CommonResult) ResultUtil.success(ResultEnum.SUCCESS,list);
        }catch (Exception e){
            e.printStackTrace();
            return (CommonResult) ResultUtil.error(ResultEnum.ERROR);
        }
    }

    //近期即将开考列表
    @ApiOperation(value = "近期即将开考列表")
    @UserLoginToken
    @PostMapping("/aboutExam")
    public CommonResult<Object> aboutExam(HttpServletRequest request){
        String  token = request.getHeader("token");
        String userId = JwtUtil.getUserId(token);
        try {
            // 用户信息
            UserDetailsGather userDetailsGather = userInfo(userId);
            // 用户分组
            List userGroup = userGroup(userId);

            String startTime = DateUtils.tomorrowDateStr() + " 00:00:00";
            String endTime = DateUtils.tomorrowDateStr() + " 23:59:59";
            QueryWrapper<ExamTarget> queryWrapper = new QueryWrapper<ExamTarget>();
            queryWrapper.eq("release_state","1");
            queryWrapper.eq("type","1");
            queryWrapper.eq("timing_type","2");
            queryWrapper.ge("timing_start_time",startTime);
            queryWrapper.le("timing_end_time",endTime);
            if(userGroup.size() > 0){
                queryWrapper.and(i -> i.eq("exam_target_type","0").eq("exam_target", userDetailsGather.getOrganizationId())
                        .or(a -> a.eq("exam_target_type", "1").in("exam_target", userGroup)));
            }else{
                queryWrapper.and(i -> i.eq("exam_target_type","0").eq("exam_target", userDetailsGather.getOrganizationId()));
            }
            queryWrapper.orderByAsc("release_time");
            List<ExamTarget> list = iExamTargetService.list(queryWrapper);

            for (ExamTarget examTarget : list) {
                QueryWrapper<LExamUser> lExamUserQueryWrapper = new QueryWrapper<LExamUser>();
                lExamUserQueryWrapper.eq("exam_id",examTarget.getExamId());
                lExamUserQueryWrapper.eq("user_id",userId);
                LExamUser lExamUser = ilExamUserService.getOne(lExamUserQueryWrapper);
                if(null != lExamUser){
                    examTarget.setUserExam("1");
                }else{
                    examTarget.setUserExam("0");
                }
                LOrganization lOrganization = ilOrganizationService.getById(examTarget.getOrganizationId());
                if(null != lOrganization)
                    examTarget.setOrganizationName(lOrganization.getOrganizationName());
                LExamSort lExamSort = ilExamSortService.getById(examTarget.getExamSortId());
                if(null != lExamSort)
                    examTarget.setExamSortName(lExamSort.getExamSortName());
            }
            return (CommonResult) ResultUtil.success(ResultEnum.SUCCESS,list);
        }catch (Exception e){
            e.printStackTrace();
            return (CommonResult) ResultUtil.error(ResultEnum.ERROR);
        }
    }

    //考试排行
    @ApiOperation(value = "考试排行")
    @UserLoginToken
    @PostMapping("/rankingExam")
    public CommonResult<Object> rankingExam(){
        try {
            QueryWrapper<LExamUser> queryWrapper = new QueryWrapper<LExamUser>();
            queryWrapper.select("exam_id,count(*) as examCount");
            queryWrapper.groupBy("exam_id");
            queryWrapper.orderByDesc("examCount");
            queryWrapper.last("limit 0,10");
            List<LExamUser> lExamUserList = ilExamUserService.list(queryWrapper);
            List<Map<String,Object>> list = new ArrayList<>();
            for (LExamUser lExamUser : lExamUserList) {
                Map<String,Object> map = new HashMap<>();
                map.put("id",lExamUser.getExamId());
                LExam lExam = ilExamService.getById(lExamUser.getExamId());
                map.put("name",lExam.getExamName());
                map.put("examCount",lExamUser.getExamCount());
                list.add(map);
            }
            return (CommonResult) ResultUtil.success(ResultEnum.SUCCESS,list);
        }catch (Exception e){
            e.printStackTrace();
            return (CommonResult) ResultUtil.error(ResultEnum.ERROR);
        }
    }

    //报名考试
    @ApiOperation(value = "报名考试")
    @UserLoginToken
    @PostMapping("/enrollExam")
    public CommonResult<Object> enrollExam(@RequestBody LExamUser lExamUser, HttpServletRequest request){
        String  token = request.getHeader("token");
        String userId = JwtUtil.getUserId(token);
        try {
            if(null != lExamUser){
                if(StringUtils.isEmpty(lExamUser.getExamId()))
                    return (CommonResult) ResultUtil.error(ResultEnum.NOT_EXAM);
                QueryWrapper<LExamPaper> queryWrapper = new QueryWrapper<LExamPaper>();
                queryWrapper.eq("exam_id",lExamUser.getExamId());
                queryWrapper.last("order by rand() LIMIT 1");
                LExamPaper lExamPaper = ilExamPaperService.getOne(queryWrapper);
                if(null != lExamPaper)
                    lExamUser.setExamPaperId(lExamPaper.getExamPaperId());
                lExamUser.setUserIp(OkHttps.getIpAddr(request));
                lExamUser.setUserId(Integer.parseInt(userId));
                lExamUser.setCreateTime(new Date());
                lExamUser.setExamUserState("0");
                if(ilExamUserService.save(lExamUser))
                    return (CommonResult) ResultUtil.success(ResultEnum.SUCCESS,lExamUser.getExamUserId());
            }
        }catch (Exception e){
            e.printStackTrace();
            return (CommonResult) ResultUtil.error(ResultEnum.ERROR);
        }
        return (CommonResult) ResultUtil.error(ResultEnum.ERROR);
    }

    // 用户详情
    private UserDetailsGather userInfo(String userId){
        QueryWrapper<UserDetailsGather> userDetailsGatherQueryWrapper = new QueryWrapper<UserDetailsGather>();
        userDetailsGatherQueryWrapper.eq("user_id",userId);
        UserDetailsGather userDetailsGather = iUserDetailsGatherService.getOne(userDetailsGatherQueryWrapper);
        return userDetailsGather;
    }

    // 用户分组
    private List userGroup(String userId){
        List groupId = new ArrayList();
        QueryWrapper<LGroupingUser> lGroupingUserQueryWrapper = new QueryWrapper<LGroupingUser>();
        lGroupingUserQueryWrapper.eq("user_id",userId);
        List<LGroupingUser> lGroupingUsers = ilGroupingUserService.list(lGroupingUserQueryWrapper);
        for (LGroupingUser lGroupingUser : lGroupingUsers) {
            groupId.add(lGroupingUser.getGroupingId());
        }
        return groupId;
    }
}
